package me.shurufa.activities;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;

import java.util.HashMap;
import java.util.Map;

import butterknife.Bind;
import de.greenrobot.event.EventBus;
import me.shurufa.R;
import me.shurufa.event.EventObject;
import me.shurufa.fragments.SearchFragment;
import me.shurufa.model.Book;
import me.shurufa.net.API;
import me.shurufa.net.BaseResponse;
import me.shurufa.net.RequestServerTask;
import me.shurufa.utils.Constants;
import me.shurufa.utils.Global;
import me.shurufa.utils.HttpUtil;
import me.shurufa.utils.LogUtils;
import me.shurufa.utils.Utils;
import me.shurufa.widget.colordialog.ColorDialog;

/**
 * 在发现页点击新建跳转的页面
 *
 * @FileName: me.shurufa.activities.NewDigestActivity.java
 * @author: kHRYSTAL
 * @email: 723526676@qq.com
 * @date: 2016-01-28 10:23
 */
public class NewDigestActivity extends BaseActivity implements View.OnClickListener, TextWatcher, TextView.OnEditorActionListener {

    public static final int SCAN_REQUEST_CODE = 3927;

    @Bind(R.id.left_text)
    TextView leftText;
    @Bind(R.id.right_image)
    ImageView rightImage;
    @Bind(R.id.right_text)
    TextView rightText;
    @Bind(R.id.toolbar_divider)
    View toolbarDivider;
    @Bind(R.id.search_edit)
    EditText searchEdit;
    @Bind(R.id.search_clear)
    ImageView searchClear;
    @Bind(R.id.go_qrcode)
    ImageView goQrcode;
    @Bind(R.id.fragment_container)
    FrameLayout fragmentContainer;

    SearchFragment[] fragments;
    int searchType = -1;
    private InputMethodManager imm;


    @Override
    public void onCreate(Bundle savedInstanceState) {
        activity_layout_res = R.layout.activity_new_digest;
        super.onCreate(savedInstanceState);
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
        uiInit();
    }

    private void uiInit() {
        imm = (InputMethodManager) this.getSystemService(Context.INPUT_METHOD_SERVICE);
        leftText.setText(getString(R.string.cancel));
        backInToolbar.setVisibility(View.GONE);
        leftText.setVisibility(View.VISIBLE);
        titleTextView.setText(getString(R.string.new_book));
        toolbarDivider.setVisibility(View.GONE);
        leftText.setOnClickListener(this);
        goQrcode.setOnClickListener(this);
        fragments = new SearchFragment[2];
        searchClear.setOnClickListener(this);
        searchEdit.addTextChangedListener(this);
        searchEdit.setOnEditorActionListener(this);
        switchSearchType(0);
        switchSearchType(1);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.left_text:
                finish();
                break;
            case R.id.go_qrcode:
                Intent intent = new Intent(NewDigestActivity.this,QRScanActivity.class);
                startActivityForResult(intent,SCAN_REQUEST_CODE);
                break;
            case R.id.search_clear:
                searchEdit.setText("");
                break;
        }
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode==SCAN_REQUEST_CODE){
            if (resultCode == QRScanActivity.RESULT_CODE){
                String isbn = data.getStringExtra(Constants.EXTRA_SCAN_RESULT);
                if (!TextUtils.isEmpty(isbn)){
                    switchSearchType(Constants.SEARCH_BY_ISBN);
                    search(isbn);
                    fragmentContainer.setVisibility(View.VISIBLE);
                }
            }
        }
    }

//    EditText Listener

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {

    }

    @Override
    public void afterTextChanged(Editable s) {
        searchClear.setVisibility(s.length() == 0 ? View.INVISIBLE : View.VISIBLE);
        switchSearchType(Constants.SEARCH_BY_KEYWORD);
        fragmentContainer.setVisibility(s.length()==0?View.GONE:View.VISIBLE);
    }

    @Override
    public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
        if (actionId == EditorInfo.IME_ACTION_SEARCH||(event!=null && event.getKeyCode() == KeyEvent.KEYCODE_ENTER)) {
            String text = v.getText().toString();
            switchSearchType(Constants.SEARCH_BY_KEYWORD);
            search(text);
            imm.hideSoftInputFromWindow(v.getWindowToken() , 0);
            return true;
        }
        return false;
    }

    public void search(String text) {
        if (text.length() == 0) {
            fragmentContainer.setVisibility(View.GONE);
            return;
        }
        SearchFragment searchFragment = fragments[searchType];
        searchFragment.searchKey = text;
        searchFragment.refresh();
    }

    void switchSearchType(int type) {
        if (type == searchType)
            return;
        Fragment oldFragment = null;
        if (searchType >= 0)
            oldFragment = fragments[searchType];
        searchType = type;
        FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
        if (oldFragment != null)
            ft.hide(oldFragment);

        SearchFragment newFragment = fragments[searchType];
        if (newFragment == null) {
            switch (searchType) {
                case 0:
                    newFragment = SearchFragment.newInstance(Constants.SEARCH_BY_ISBN);
                    break;
                case 1:
                    newFragment = SearchFragment.newInstance(Constants.SEARCH_BY_KEYWORD);
                    break;
            }
            fragments[searchType] = newFragment;
        }
        if (newFragment != null) {
            if (!newFragment.isAdded()) {
                ft.add(R.id.fragment_container, newFragment, String.valueOf(searchType));
            }
            ft.show(newFragment);
        }
        ft.commitAllowingStateLoss();
        String text = searchEdit.getText().toString();
        if (text.length() > 0) {
            newFragment.searchKey = text;
            final SearchFragment finalNewFragment = newFragment;
//            searchEdit.postDelayed(new Runnable() {
//                @Override
//                public void run() {
                    finalNewFragment.refreshShowPtr();
//                }
//            }, 300);
        }
    }

    public void onEventMainThread(EventObject object) {
        if (object.getEventAction().equals(Constants.EVENT_STAR_BOOK)){
            final Book book = object.getBook();
            if (Global.DEBUG)
                Utils.showToast("bookId:"+book.id+"\n"+"externalBookId:"+book.external_book_id);
            ColorDialog dialog = new ColorDialog(this);
            dialog.setAnimationEnable(true);
            dialog.setTitle(getString(R.string.add_to_shelves));
            dialog.setContentText(getString(R.string.positive_to_add));
            dialog.setPositiveListener(getString(R.string.ok), new ColorDialog.OnPositiveListener() {
                @Override
                public void onClick(ColorDialog dialog) {
                    dialog.dismiss();
                    new RequestServerTask<BaseResponse>(BaseResponse.class,NewDigestActivity.this,getString(R.string.commit_pls_wait)){
                        @Override
                        protected String requestServer() {
                            Map<String,Object> params = new HashMap<String, Object>();
                            LogUtils.kLog().e("bookId = "+ book.id+",externalBookId = "+ book.external_book_id);
                            if (book.bid!=0L)
                                params.put("bookId",book.bid);
                            else
                                params.put("externalBookId",book.external_book_id);
                            params.put("token", Global.currentUser.token);
                            return HttpUtil.post(API.ADD_BOOK_TO_SHELVES,params);
                        }

                        @Override
                        protected void onSuccess(BaseResponse result) {
                             if (result.success){
                                 EventBus.getDefault().post(new Intent(Constants.ACTION_BOOKSHELVES_REFRESH));
                                 NewDigestActivity.this.finish();
                             }
                        }
                    }.start();
                }
            })
                    .setNegativeListener(getString(R.string.cancel), new ColorDialog.OnNegativeListener() {
                        @Override
                        public void onClick(ColorDialog dialog) {
                            dialog.dismiss();
                        }
                    }).show();
        }
    }
}
